package com.njupt.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.njupt.exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.*;
import java.util.*;

public class BeanValidator {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T>Map<String,String> validate(T t, Class... groups){
        Validator validator = validatorFactory.getValidator();
        Set validatorResult = validator.validate(t,groups);
        if(validatorResult.isEmpty()){
            return Collections.EMPTY_MAP;
        }else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validatorResult.iterator();
            while(iterator.hasNext()){
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return errors;
        }
    }

    public static Map<String,String> validateList(Collection<?> collection){
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;
        do{
            if(!iterator.hasNext()){
                return Collections.EMPTY_MAP;
            }
            Object object = iterator.next();
            errors = validate(object,new Class[0]);
        }while (errors.isEmpty());
        return errors;
    }

    public static Map<String,String> validateObject(Object first,Object... objects){
        if(objects != null && objects.length > 0){
            return validateList(Lists.asList(first,objects));
        }else {
            return validate(first,new Class[0]);
        }
    }

    //这里不返回具体的参数校验错误信息，而是直接抛出异常
    public static void check(Object param) throws ParamException{
        Map<String,String> map = BeanValidator.validateObject(param);
//        if(map != null && map.entrySet().size()>0){
//            throw new ParamException(map.toString());
//        }
        if(MapUtils.isEmpty(map)){
            throw new ParamException(map.toString());
        }
    }
}
